package com.woniuxy.demo.epai.service.impl;

import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.demo.epai.config.Alipay;
import com.woniuxy.demo.epai.dao.*;
import com.woniuxy.demo.epai.model.*;
import com.woniuxy.demo.epai.service.AliPayService;
import com.woniuxy.demo.epai.service.IProductService;
import com.woniuxy.demo.epai.vo.Alivo;
import com.woniuxy.demo.epai.vo.ArecordVo;
import com.woniuxy.demo.epai.vo.OrderVo;
import com.woniuxy.demo.epai.vo.RecordVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Transactional
@Slf4j
public class AliPayServiceImpl implements AliPayService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private OrderMapper orderMapper;
    @Autowired
    private Alipay alipay;
    @Resource
    private MembersMapper membersMapper;
    @Resource
    private OrderServiceImpl orderService;
    @Resource
    private WalletMapper walletMapper;
    @Resource
    private IProductService iProductService;
    @Resource
    private BmsTreasureCountMapper bmsTreasureCountMapper;
    @Resource
    private AuctionRecordMapper auctionRecordMapper;

    /**
     * 支付接口
     * @param alivo
     * @return
     */
    @Override
    public String aliPay(Alivo alivo){

        String pay = null;
        try {
            pay = alipay.pay(alivo);

            return pay;
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return null;
        }

    }

    //支付成功后运行的逻辑代码
    @Override
    public void aliSuccess(OrderVo orderVo) {

        User user = userMapper.selectById(orderVo.getUid());
        Integer uid = orderVo.getUid();
        //判断用户是否是会员，如果是则修改用户的会员成长值和信用分
        if (user.getIsVIP()==1){
            //支付成功后修改订单状态为2
            orderMapper.updateOrderStaus(2,orderVo.getOid());
            //修改redis中订单状态
            orderService.updateRedisOrderStatus(orderVo.getOid(),2);
            //调整用户的信用分和会员成长值
            QueryWrapper<Members> membersQueryWrapper = new QueryWrapper<>();
            membersQueryWrapper.eq("uid",uid);
            Members members = membersMapper.selectOne(membersQueryWrapper);
            //信用积分加2
            members.setCredit(members.getCredit()+2);
            //会员成长值加成交金额的10%
            int i = orderVo.getPrice().intValue();
            Double v = (i * 0.1);
            int i1 = v.intValue();
            members.setGrouth(members.getGrouth()+ i1);
            //将修改后的值传入数据库
            membersMapper.updateById(members);
            //通过商品id去查找卖家钱包信息
            //获取商品信息
            Product product = iProductService.queryProductById(orderVo.getPid());
            //查询卖家钱包信息
            Wallet wallet = walletMapper.selectById(product.getUid());
            //将交易价格转为BigDecimal类型
            BigDecimal bigDecimal = orderVo.getPrice();
            //计算平台收取的手续费额度
            BigDecimal multiply = bigDecimal.multiply(new BigDecimal(0.01));
            //计算卖家应收取的金额
            BigDecimal subtract = bigDecimal.subtract(multiply);

            //修改卖家余额
            wallet.setAccount(wallet.getAccount().add(subtract));
            walletMapper.updateById(wallet);

            //平台收取手续费

            //创建一个平台资产的对象
            BmsTreasureCount bmsTreasureCount = new BmsTreasureCount();
            //填入收入类型
            bmsTreasureCount.setType("手续费");
            //填入订单号
            bmsTreasureCount.setOid(orderVo.getOid());
            //填入金额
            bmsTreasureCount.setAmount(multiply);
            //填入订单完成时间
            bmsTreasureCount.setTime(new Date(System.currentTimeMillis()));
            //将对象存入数据库
            bmsTreasureCountMapper.insert(bmsTreasureCount);

            //扣除买家的保证金发放给卖家


            //获取该商品需缴纳的保证金
            OrderVo bond = orderMapper.findBond(orderVo.getOid());
            //获取买家被冻结的保证金余额
            Wallet wallet1 = walletMapper.selectById(uid);
            //扣除买家保证金
            wallet1.setAccount(wallet1.getAccount().subtract(bond.getBond()));
            walletMapper.updateById(wallet1);
            orderService.run(orderVo.getOid(),false,uid);
        }else{
            //支付成功后修改订单状态为2
            orderMapper.updateOrderStaus(2,orderVo.getOid());
            //修改redis中订单状态
            orderService.updateRedisOrderStatus(orderVo.getOid(),2);
            //将剩余支付时间关闭
            orderService.run(orderVo.getOid(),false,uid);
            //通过商品id去查找卖家钱包信息
            //获取商品信息
            Product product = iProductService.queryProductById(orderVo.getPid());
            //查询卖家钱包信息
            Wallet wallet = walletMapper.selectById(product.getUid());
            //将交易价格转为BigDecimal类型
            BigDecimal bigDecimal = orderVo.getPrice();
            //计算平台收取的手续费额度
            BigDecimal multiply = bigDecimal.multiply(new BigDecimal(0.01));
            //计算卖家应收取的金额
            BigDecimal subtract = bigDecimal.subtract(multiply);

            //修改卖家余额
            wallet.setAccount(wallet.getAccount().add(subtract));
            walletMapper.updateById(wallet);

            //平台收取手续费

            //创建一个平台资产的对象
            BmsTreasureCount bmsTreasureCount = new BmsTreasureCount();
            //填入收入类型
            bmsTreasureCount.setType("手续费");
            //填入订单号
            bmsTreasureCount.setOid(orderVo.getOid());
            //填入金额
            bmsTreasureCount.setAmount(multiply);
            //填入订单完成时间
            bmsTreasureCount.setTime(new Date(System.currentTimeMillis()));
            //将对象存入数据库
            bmsTreasureCountMapper.insert(bmsTreasureCount);

            //扣除买家的保证金发放给卖家


            //获取该商品需缴纳的保证金
            OrderVo bond = orderMapper.findBond(orderVo.getOid());
            //获取买家被冻结的保证金余额
            Wallet wallet1 = walletMapper.selectById(uid);
            //扣除买家保证金
            wallet1.setAccount(wallet1.getAccount().subtract(bond.getBond()));
            walletMapper.updateById(wallet1);
        }
    }

    /**
     * 支付接口
     * @param alivo
     * @return
     */
    @Override
    public String aliPayDoPai(Alivo alivo){

        String pay = null;
        try {
            pay = alipay.pay_dopai(alivo);
            return pay;
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return null;
        }

    }
    //竞价成功后运行的逻辑代码
    @Override
    @Transactional
    public boolean dopaiSuccess(RecordVo recordVo) {
        List<ArecordVo> arecordVoById = auctionRecordMapper.getArecordVoById(recordVo.getId());
        ArecordVo arecordVo = null;
        if (!ObjectUtils.isEmpty(arecordVoById)){
            //有进价记录取最新
            arecordVo = arecordVoById.get(arecordVoById.size()-1);
            if(arecordVo.getUid()==recordVo.getUid()){
                return false;
            }
        }else{
            //无竞价记录创建
            AuctionRecord auctionRecord = new AuctionRecord();
            auctionRecord.setUid(recordVo.getUid());
            auctionRecord.setPid(recordVo.getId());
            auctionRecord.setMoney(recordVo.getMoney());
            auctionRecord.setTime(new Date());
            auctionRecordMapper.addAuctionRecord(auctionRecord);
            return true;
        }
        log.info("查询竞价记录{}，最新{}",arecordVoById,arecordVo);
        //出价判断不低于最高价
        if (arecordVo.getMoney().compareTo(recordVo.getMoney())<0){
            AuctionRecord auctionRecord = new AuctionRecord();
            auctionRecord.setUid(recordVo.getUid());
            auctionRecord.setPid(recordVo.getId());
            auctionRecord.setMoney(recordVo.getMoney());
            auctionRecord.setTime(new Date());
            auctionRecordMapper.addAuctionRecord(auctionRecord);
            return true;
        }else {
            return false;
        }

    }


}
